package com.quasar.hpatient.view;

import android.os.CountDownTimer;
import android.support.v7.widget.Toolbar;
import android.text.InputFilter;
import android.text.LoginFilter;
import android.text.Selection;
import android.text.Spannable;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.text.style.ForegroundColorSpan;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.quasar.hpatient.MainAppliaction;
import com.quasar.hpatient.R;
import com.quasar.hpatient.base.BaseActivity;
import com.quasar.hpatient.constant.ConstantManger;
import com.quasar.hpatient.model.httpmodel.DataStateResult;
import com.quasar.hpatient.model.medicalmodel.PatientInfoData;
import com.quasar.hpatient.model.operationmodel.AccountInfo;
import com.quasar.hpatient.onInterface.AnotherResultListener;
import com.quasar.hpatient.onInterface.LoginResultListener;
import com.quasar.hpatient.presenter.LoginPresenter;
import com.quasar.hpatient.presenter.PostRegisterPresenter;
import com.quasar.hpatient.utils.LogAndToastUtil;
import com.quasar.hpatient.utils.Spanny;
import com.quasar.hpatient.utils.StringUtils;
import com.quasar.hpatient.utils.UrlUtils;
import com.quasar.hpatient.view.personal.register.RegisterEditActivity_;
import com.vise.log.ViseLog;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.ViewById;

import cn.bmob.sms.BmobSMS;
import cn.bmob.sms.exception.BmobException;
import cn.bmob.sms.listener.RequestSMSCodeListener;
import cn.bmob.sms.listener.VerifySMSCodeListener;

/**
 * author : 许建宏
 * Date: 2017/10/7 0026
 * View:注册
 */

@EActivity(R.layout.activity_register)
public class RegisterActivity extends BaseActivity implements AnotherResultListener<DataStateResult>,LoginResultListener<PatientInfoData> {

    private static final String TAG = "RegisterActivity";
    private PostRegisterPresenter postRegisterPresenter;
    private LoginPresenter loginPresenter;
    //短信倒计时
    int count = 60;
    boolean SoPwd = true;

    //点击显示密码
    @ViewById(R.id.pwdShow)
    ImageView pwdShow;
    @ViewById(R.id.main_toolbar)
    Toolbar main_toolbar;
    //手机号码
    @ViewById(R.id.et_userPhone)
    EditText et_userPhone;
    //短信
    @ViewById(R.id.et_verification)
    EditText et_verification;
    //密码
    @ViewById(R.id.et_password)
    EditText et_password;
    //重复密码
    @ViewById(R.id.et_confirm_password)
    EditText et_confirm_password;
    @ViewById(R.id.tv_existence)
    TextView tv_existence;
    //获取短信验证码
    @ViewById(R.id.sms)
    TextView sms;



    @AfterViews
    void init() {
        initView();
        initData();
    }

    /**
     * 初始化控件
     */
    @Override
    protected void initView() {
        initToolbar();
        editTextinit();
        Spanny spanny = new Spanny();
        spanny.append("已有账号,", new ForegroundColorSpan(color(R.color.btn_press)));
        spanny.append("点击登录", new ForegroundColorSpan(color(R.color.btcolor)));
        tv_existence.setText(spanny);
        LoginFilter.UsernameFilterGeneric u = new LoginFilter.UsernameFilterGeneric();
        InputFilter[] fs = {u};
        et_userPhone.setFilters(fs);
        et_password.setFilters(fs);
        et_confirm_password.setFilters(fs);

        et_userPhone.setFilters(new InputFilter[]{new InputFilter.LengthFilter(11)});  //限制最多输入11位
        et_password.setFilters(new InputFilter[]{new InputFilter.LengthFilter(25)});  //限制最多输入25位
        et_confirm_password.setFilters(new InputFilter[]{new InputFilter.LengthFilter(25)});
    }

    @Override
    protected void initData() {
        postRegisterPresenter=new PostRegisterPresenter(this);
        loginPresenter=new LoginPresenter(this);
    }

    //获取短信
    @Click(R.id.sms)
    public void sms() {
        String phone = et_userPhone.getText().toString().trim();
        if (!phone.matches(StringUtils.isPhone)) {
            et_userPhone.setError("手机号码不合法");
            return;
        }

        if (phone.length() != 11) {
            et_userPhone.requestFocus();
            et_userPhone.setError("请输入手机号");
            return;
        }

        BmobSMS.requestSMSCode(this, phone, ConstantManger.SMS, new RequestSMSCodeListener() {
            @Override
            public void done(Integer integer, BmobException e) {
                if (e == null) {
                    LogAndToastUtil.toast(RegisterActivity.this, "短信已发送");
                    sms.setEnabled(false);   //不可点击
                    countDownTimer(); //倒计时
                }
            }
        });
    }

    /**
     * 密码的可见/不可见
     */
    @Click(R.id.pwdShow)
    public void pwdShow() {
        if (SoPwd) {
            et_confirm_password.setTransformationMethod(HideReturnsTransformationMethod.getInstance());
            pwdShow.setImageResource(R.mipmap.ic_no);
        } else {
            //设置EditText文本为隐藏的
            et_confirm_password.setTransformationMethod(PasswordTransformationMethod.getInstance());
            pwdShow.setImageResource(R.mipmap.ic_so);
        }
        SoPwd = !SoPwd;

        et_confirm_password.postInvalidate();
        CharSequence charSequence = et_confirm_password.getText();

        if (charSequence instanceof Spannable) {
            Spannable spanText = (Spannable) charSequence;
            Selection.setSelection(spanText, charSequence.length());
        }
    }

    /**
     * 提交
     */
    @Click(R.id.bt_login)
    public void bt_login() {

        String name = et_userPhone.getText().toString().trim();
        String pwd1 = et_password.getText().toString().trim();
        String pwd2 = et_confirm_password.getText().toString().trim();
        String smsValue = et_verification.getText().toString().trim();
        if (!name.matches(StringUtils.isPhone)) {
            et_userPhone.requestFocus();
            et_userPhone.setError("手机号码不合法");
            return;
        }
        if (smsValue.length() == 0) {
            et_verification.requestFocus();
            et_verification.setError("请输入验证码");
            return;
        }


        if (pwd1.length() < 6) {
            et_password.requestFocus();
            et_password.setError("密码格式不正确");
            return;
        }

        if (!pwd1.equals(pwd2)) {
            et_confirm_password.requestFocus();
            et_confirm_password.setText("");
            et_confirm_password.setError("两次密码不一致");
            return;
        }

        if (!StringUtils.PwdContainsStr(pwd2)) {
            et_password.setError("密码格式不正确");
            et_password.setText("");
            et_password.requestFocus();
            et_confirm_password.setText("");
            return;
        }
        VerificationSms(name,pwd2);

//        postRegisterPresenter.LoginPresenterOperation(name,pwd2);

    }

    //已有账号点击返回
    @Click(R.id.ll_finsh)
    public void ll_finsh() {
        finish();
    }


    /**
     * 进行倒计时
     */
    private void countDownTimer() {
        new CountDownTimer(60000, 1000) {

            @Override
            public void onTick(long millisUntilFinished) {
                if (count != 0) {
                    count--;
                    sms.setText(count + "s");
                }
            }

            //倒计时完成
            @Override
            public void onFinish() {
                count = 60;
                sms.setText(count + "s");
                sms.setEnabled(true);// 可点击
                sms.setText("获取验证码");
            }
        }.start();
    }

    /**
     * 验证短信是否成功
     *
     */
    public void VerificationSms(final String name, final String pwd) {

        String smsvalue = et_userPhone.getText().toString().trim();
        BmobSMS.verifySmsCode(this, smsvalue, et_verification.getText().toString().trim(),
                new VerifySMSCodeListener() {

                    @Override
                    public void done(BmobException ex) {
                        // TODO Auto-generated method stub
                        if (ex == null) {// 短信验证码已验证成功
                            Log.d(TAG, "验证通过");
                            showDialog();
                            postRegisterPresenter.LoginPresenterOperation(name,pwd);
                        } else {
                            Log.d(TAG, "验证失败: " + ex.getErrorCode() + ",msg = " + ex.getLocalizedMessage());
                            LogAndToastUtil.toast(RegisterActivity.this, "验证码输入失败", "");
                        }
                    }
                });
    }

    private int color(int value) {
        return this.getResources().getColor(value);
    }

    @Override
    public void onSuccess(DataStateResult data) {
        String name = et_userPhone.getText().toString().trim();
        String pwd2 = et_confirm_password.getText().toString().trim();
        MainAppliaction.getInstance().setPwd(pwd2);
        MainAppliaction.getInstance().setUserName(name);
        loginPresenter.LoginPresenterOperation(name,pwd2);
    }

    @Override
    public void onError(String msg) {
        if(msg!=null){
            msg(msg);
        }
        dessDialog();
        Log.d(TAG, "onError: " + msg);
    }

    @Override
    public void onRefreshUI() {
//        finish();
    }


    @ViewById(R.id.del_userPhone)
    ImageView del_userPhone;
    @ViewById(R.id.del_password)
    ImageView del_password;
    @ViewById(R.id.del_confirm)
    ImageView del_confirm;

    @Click(R.id.del_userPhone)
    public void del_userPhone(){
        et_userPhone.setText("");
    }
    @Click(R.id.del_password)
    public void del_password(){
        et_password.setText("");
    }
    @Click(R.id.del_confirm)
    public void del_confirm(){
        et_confirm_password.setText("");
    }

    public void editTextinit() {

        et_userPhone.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {

                if (hasFocus) {
                    del_userPhone.setVisibility(View.VISIBLE);
                } else {
                    del_userPhone.setVisibility(View.GONE);
                }
            }
        });


        et_password.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {

                if (hasFocus) {
                    del_password.setVisibility(View.VISIBLE);
                } else {
                    del_password.setVisibility(View.GONE);
                }
            }
        });



        et_confirm_password.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {

                if (hasFocus) {
                    del_confirm.setVisibility(View.VISIBLE);
                } else {
                    del_confirm.setVisibility(View.GONE);
                }
            }
        });
    }

    @Override
    public void onLoginSuccess(PatientInfoData data) {
        dessDialog();
        AccountInfo.saveAccount(RegisterActivity.this, data);
        finish();
        //注册完成进入患者完成个人信息界面
        RegisterEditActivity_.intent(this).start();
    }

    @Override
    public void onLoginError(String msg) {
        ViseLog.d("onError"+msg);
        if(msg!=null){
            msg(msg);
        }
        dessDialog();
    }

    @Override
    public void onLoginRefreshUI() {

    }
}
